<template>
  <div>
    <page-loading
      :loading.sync="pageLoading"
      :error.sync="pageError"
      :enable-pull-refresh="false"
      @reload="getDetail"
    >
      <template v-if="hasInfo">
        <video-player
          class="vp"
          :url="videoPlayUrl"
          :poster="videoInfo.pic"
          :duration="videoInfo.duration"
          @soketSend="soketSend"
          :videoInfo="videoInfo"
        />
        <van-tabs
          ref="vanTabs"
          class="tabs"
          v-model="activeTab"
          :title-active-color="rootThemeColor"
          animated
          @change="onTabChange"
        >
          <van-tab title="简介">
            <video-info :info="videoInfo" :tags="videoTags" />
            <video-toolbar
              :fav-checked="favStatus"
              :share-pic="videoInfo.pic"
              :share-title="videoInfo.title"
              @fav-click="onFavClick"
            />

            <ul class="bar-os">
              <li>
                <i class="iconfont icon-zan1"></i>
                <h6>1.6万</h6>
              </li>
              <li>
                <i class="iconfont icon-zan1-copy"></i>
                <h6>不喜欢</h6>
              </li>
              <li>
                <i class="iconfont icon-dashang"></i>
                <h6>3386</h6>
              </li>
              <li>
                <i class="iconfont icon-shoucangtianchong"></i>
                <h6>4542</h6>
              </li>
              <li>
                <i class="iconfont icon-zhuanfa"></i>
                <h6>338</h6>
              </li>
            </ul>

            <video-part
              v-if="hasParts"
              :parts="videoInfo.pages"
              :current-part.sync="videoInfo.cid"
              @select="onSelectPart"
            />
            <video-related :videos="relatedVideos" />
          </van-tab>
          <van-tab>
            <template #title
              >评论 {{ videoInfo.stat.reply | formatNumber }}</template
            >
            <video-comment :comments="videoComments" popup-class="bpopup" />
          </van-tab>
        </van-tabs>
      </template>
    </page-loading>
  </div>
</template>

<script>
import PageLoading from '@/components/page-loading/PageLoading.vue'
import VideoPlayer from '@/components/video-player/VideoPlayer.vue'
import VideoInfo from '@/components/video/VideoInfo.vue'
import VideoToolbar from '@/components/video/VideoToolbar.vue'
import VideoPart from '@/components/video/VideoPart.vue'
import VideoRelated from '@/components/video/VideoRelated.vue'
import VideoComment from '@/components/comment/Comment.vue'
import {
  apiGetDetail,
  apiGetPlayUrl,
  apiGetVideoTags,
  apiGetVideoRelated,
  apiGetVideoComment
} from '@/api/video.js'
import { getStorage, setStorage } from '@/utils/localStorage.js'
import { formatNumber } from '@/filters/filters.js'
import pageLoadingMixin from '@/mixins/pageLoading'
import { Tabs as VanTabs, Tab as VanTab } from 'vant'
export default {
  name: 'Video',
  inject: [
    'rootRouter',
    'rootThemeColor',
    'rootRouter',
    'routerConfig',
    'rootTitle',
    'rootKeyword',
    'rootSend'
  ],
  mixins: [pageLoadingMixin],
  metaInfo () {
    return {
      title: this.title,
      meta: [
        { name: 'keywords', content: this.keywords },
        { name: 'description', content: this.description }
      ]
    }
  },
  components: {
    PageLoading,
    VideoPlayer,
    VanTabs,
    VanTab,
    VideoInfo,
    VideoToolbar,
    VideoPart,
    VideoRelated,
    VideoComment
  },
  props: {
    // 视频bvid
    bvid: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      videoId: this.bvid,
      videoInfo: null,
      videoPlayUrl: null,
      videoTags: [],
      relatedVideos: [],
      videoComments: [],
      activeTab: 0,
      favStatus: false
    }
  },
  computed: {
    title () {
      let word = this.rootTitle
      if (this.hasInfo) {
        word = `${this.videoInfo.title}_${word}`
      }
      return word
    },
    keywords () {
      let word = this.rootKeyword
      if (this.hasInfo) {
        word = `${this.videoInfo.title},${this.breadcrumb.name},${this.breadcrumb.subName},${word}`
      }
      return word
    },
    description () {
      let word = ''
      if (this.hasInfo) {
        word =
          (this.videoInfo.desc || '').replace(/\n/g, '').substring(0, 200) ||
          this.videoInfo.title
      }
      return word
    },
    hasInfo () {
      return this.videoInfo !== null
    },
    hasParts () {
      return this.hasInfo && this.videoInfo.pages.length > 1
    },
    breadcrumb () {
      const result = {}
      for (const config of this.routerConfig) {
        const { name, tid, sub, hide } = config
        if (sub) {
          let match = false
          for (const subConfig of sub) {
            const subTid = subConfig.tid
            if (this.videoInfo.tid === subTid) {
              match = true
              result.name = name
              result.tid = tid
              result.hide = hide
              result.subName = subConfig.name
              result.subTid = subConfig.tid
              result.subHide = subConfig.hide
              break
            }
          }
          if (match) {
            break
          }
        }
      }
      return result
    }
  },
  filters: {
    formatNumber
  },
  created () {
    this.getDetail()
  },
  mounted () {},
  watch: {
    bvid (newVal) {
      this.videoId = newVal
    },
    videoId (newVal) {
      this.pageError = false
      this.videoComments = []
      this.getDetail()
    }
  },
  methods: {
    soketSend (obj) {
      this.rootSend(obj)
    },
    // 获取视频基本信息和播放地址
    getDetail () {
      apiGetDetail({
        bvid: this.videoId
      })
        .then(res => {
          const { code, data } = res
          if (code === 0 && data !== null) {
            this.videoInfo = data
            sessionStorage.videoInfo = JSON.stringify(data)

            const obj = {
              type: sessionStorage.dataNum,
              messageType: 1,
              videoId: this.videoInfo.bvid,
              videoName: this.videoInfo.title
            }
            this.soketSend(obj)

            this.initFav()
          } else {
            this.pageError = true
          }
          return data
        })
        .then(result => {
          if (typeof result.redirect_url !== 'undefined') {
            const id = result.redirect_url.substring(
              result.redirect_url.lastIndexOf('/') + 1
            )
            this.rootRouter.push({ name: 'bangumi', params: { id } })
          } else {
            const { aid, bvid, cid } = result
            this.getRelatedVideo(aid, bvid)
            this.getVideoPlayUrl(aid, bvid, cid)
            this.getVideoTags(aid, bvid)
          }
        })
        .catch(() => {
          this.rootRouter.replace({ name: '404' })
          // this.pageError = true
        })
        .finally(() => {
          this.pageLoading = false
        })
    },
    // 获取视频播放地址
    getVideoPlayUrl (aid, bvid, cid) {
      apiGetPlayUrl({
        cid,
        aid,
        bvid
      })
        .then(res => {
          const { code, data } = res
          if (code === 0 && data !== null) {
            const { durl } = data
            this.videoPlayUrl = durl[0].url
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 获取视频标签
    getVideoTags (aid, bvid) {
      apiGetVideoTags({
        aid,
        bvid
      })
        .then(res => {
          const { code, data } = res
          if (code === 0 && data !== null) {
            this.videoTags = data
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 获取和此视频类似的其他视频
    getRelatedVideo (aid, bvid) {
      apiGetVideoRelated({
        aid,
        bvid
      })
        .then(res => {
          const { code, data } = res
          if (code === 0 && data !== null) {
            this.relatedVideos = data.slice(0, 30)
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 获取视频的评论
    getVideoComment (aid, bvid) {
      apiGetVideoComment({
        aid,
        bvid
      })
        .then(res => {
          const { code, data } = res
          if (code === 0 && data !== null) {
            const { replies } = data
            this.videoComments = replies
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    onTabChange (name) {
      if (name === 1 && !this.videoComments.length) {
        // 评论标签首次加载
        const { aid, bvid } = this.videoInfo
        this.getVideoComment(aid, bvid)
      }
    },
    // 存储设置缓存
    setHistory ({ type, data, action = 'add' } = {}) {
      const vals = getStorage(type)
      const matchIndex = vals.findIndex(val => val.bvid === data.bvid)
      if (matchIndex === -1) {
        const {
          aid,
          bvid,
          pic,
          owner: { name },
          title
        } = data
        const item = {
          aid,
          bvid,
          pic,
          owner: name,
          title,
          isHistory: 1,
          timestamp: new Date().getTime()
        }
        vals.unshift(item)
        setStorage(type, vals)
      } else {
        if (action === 'del') {
          vals.splice(matchIndex, 1)
          setStorage(type, vals)
        }
      }
    },
    initFav () {
      const favs = getStorage('fav_history')
      const matchIndex = favs.findIndex(
        fav => fav.bvid === this.videoInfo.bvid
      )
      this.favStatus = matchIndex > -1
    },
    onFavClick () {
      this.favStatus = !this.favStatus
      this.setHistory({
        type: 'fav_history',
        data: this.videoInfo,
        action: !this.favStatus ? 'del' : ''
      })
    },
    onSelectPart (part) {
      this.getVideoPlayUrl(this.videoInfo.aid, this.videoInfo.bvid, part.cid)
    }
  }
}
</script>
<style lang="scss" scoped>
@media screen and (orientation: portrait) {
  // 竖屏
  .tabs ::v-deep .van-tabs__wrap {
    position: sticky;
    top: rem(212px);
    z-index: 2;
  }
  .vp {
    position: sticky;
    top: 0;
    z-index: 2;
  }
}
.bar-os {
  display: flex;
  width: 100%;
  justify-content: space-around;
  align-items: center;
  color: #767676;
  text-align: center;
  padding: 0 rem(10px);
  box-sizing: border-box;
  margin-bottom: rem(10px);
  i {
    font-size: rem(22px);
  }
  h6 {
    margin: rem(8px) 0;
    font-weight: normal;
  }
}
</style>
